import crypto from "crypto-js";
import axios from "axios";
import random from "string-random";
import redisClient from "~/utils/redis";
const WX_BASE_URL = "https://api.weixin.qq.com/cgi-bin";
const APP_ID = "wxc0542623380dd621";
const APP_SECRET = "708b6920d794db9b8cceb7b7d5b5a23d";

export const generatorSha1 = (str) => {
    return crypto.SHA1(str).toString(crypto.enc.Hex);
};

/**
 * 获取Access token
 * 参考：<https://developers.weixin.qq.com/doc/offiaccount/Basic_Information/Get_access_token.html>
 * 注意运行该方法的电脑ip要加到微信公众号后台的IP白名单中
 */
export const getAccessToken = async (appId, appSecret) => {
    if (!appId || !appSecret) return;
    const result = await axios.get(
        `/token?grant_type=client_credential&appid=${appId}&secret=${appSecret}`,
        { baseURL: WX_BASE_URL }
    );
    return result.data.access_token;
};

/**
 * 获签名信息
 * @param {*} url - 要分享的网页链接
 * @returns
 */
export const getSignature = async (url) => {
    if (!url) return;
    const accessToken = await getAccessToken(APP_ID, APP_SECRET);
    const getticketResult = await axios.get(
        `/ticket/getticket?access_token=${accessToken}&type=jsapi`,
        { baseURL: WX_BASE_URL }
    );
    const jsapi_ticket = getticketResult.data.ticket;
    const nonceStr = random(16); // 'Wm3WZYTPz0wzccnW'
    const timestamp = new Date().getTime();
    const str = `jsapi_ticket=${jsapi_ticket}&noncestr=${nonceStr}&timestamp=${timestamp}&url=${url}`;
    const signature = generatorSha1(str);
    const result = {
        nonceStr,
        jsapi_ticket,
        timestamp,
        url,
        signature,
        appId: APP_ID,
    };
    return result;
};

export const getOpenId = async (appid, secret, code) => {
    const accessTokenRes = await axios.get(`https://api.weixin.qq.com/sns/oauth2/access_token`, {
        params: {
            'appid': appid,
            'secret': secret,
            'code': code,
            'grant_type': 'authorization_code'
        }
    });

    return accessTokenRes.data;
}

export const checkUserAttention = async (appid, secret, openid) => {
    const accessToken2Res = await axios.get(`https://api.weixin.qq.com/cgi-bin/token`, {
        params: {
            'appid': appid,
            'secret': secret,
            'grant_type': 'client_credential'
        }
    });

    const accessToken = accessToken2Res.data.access_token;

    const userInfoRes = await axios.get('https://api.weixin.qq.com/cgi-bin/user/info', {
        params: {
            access_token: accessToken,
            openid: openid,
            lang: 'zh_CN'
        }
    });

    return userInfoRes.data;
}
